package com.base.controller;

import com.base.utils.FileHandleUtil;
import com.base.utils.Result;
import com.base.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author wnhuang
 * @Package com.base.controller
 * @date 2021-03-03 10:01
 */
@RestController
@Slf4j
public class UploadController {

    private String path = "/";

    @PostMapping("/upload")
    public Result create(@RequestPart MultipartFile file) throws IOException {
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        String uploadPath = FileHandleUtil.upload(file.getInputStream(), "image/", newName);
        System.out.println("文件存放路径为" + uploadPath);
        return ResultUtil.success(uploadPath);
    }

    @PostMapping("/upload1")
    public Result importData(MultipartFile file, HttpServletRequest req) throws IOException {
        String realPath = req.getServletContext().getRealPath("/img");
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        file.transferTo(new File(folder, newName));
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + realPath + newName;
        System.out.println(url);
        return ResultUtil.success(url);
    }

}
